package com.zc.auth.security.core.access;

import com.zc.auth.security.core.authentication.AnonymousAuthenticationToken;
import com.zc.auth.security.core.exception.AnonymousAccessDeniedException;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * 路由角色匹配决策器
 */
public class RoleUrlAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (CollectionUtils.isEmpty(configAttributes)) {
            return;
        }
        if (authentication instanceof AnonymousAuthenticationToken) {
            throw new AnonymousAccessDeniedException("不能匿名访问，请登录！");
        }
        //当前用户拥有权限和所需权限匹配 拥有一个就通过
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            for (ConfigAttribute configAttribute : configAttributes) {
                if (authority.getAuthority().equals(configAttribute.getAttribute())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("无权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
